<template>
  <div class="permission">
    <el-card>
      <!-- 按钮 -->
      <div class="box">
        <el-button type="primary" size="mini" @click="openadd(1, 0)"
          >添加菜单</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" row-key="id">
        <el-table-column prop="name" label="菜单名称"> </el-table-column>
        <el-table-column prop="code" label="权限标识"> </el-table-column>
        <el-table-column prop="description" label="描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              v-if="row.type === 1"
              @click="openadd(2, row.id)"
              >添加权限</el-button
            >
            <el-button type="text">查看api权限</el-button>
            <el-button type="text" @click="openEdit(row.id)">查看 </el-button>
            <el-button type="text" @click="shanchu(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <aded
      :adedShow.sync="adedShow"
      ref="aded"
      @update="getAllPermission"
    ></aded>
  </div>
</template>

<script>
import { getAllPermissionApi, delSysPermissionApi } from '@/api/permission'
import aded from './compoents/aded.vue'
export default {
  data () {
    return {
      tableData: [],
      // 控制弹框显示
      adedShow: false
    }
  },
  components: {
    aded
  },
  methods: {
    // 获取全部数据
    async getAllPermission () {
      const res = await getAllPermissionApi()
      this.tableData = this.turnData(res, '0')
    },
    // 使用递归修改数据
    turnData (arr, str) {
      var newarr = []
      arr.forEach(item => {
        if (item.pid === str) {
          const children = this.turnData(arr, item.id)
          item.children = children
          newarr.push(item)
        }
      })
      return newarr
    },
    // 删除权限点
    async shanchu (id) {
      try {
        console.log(id)
        await this.$confirm('确定删除吗')
        await delSysPermissionApi(id)
        this.getAllPermission()
        this.$message.success('操作成功')
      } catch {}
    },
    // 打开弹框
    openEdit (id) {
      this.adedShow = true
      this.$refs.aded.getSysPermission(id)
    },
    // 判断点击的是什么新增按钮传入数据
    openadd (type, pid) {
      this.adedShow = true
      this.$refs.aded.openadd(type, pid)
    }
  },

  created () {
    this.getAllPermission()
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
  .box {
    text-align: right;
  }
}
</style>
